<?php

namespace App\Component;

use App\Core\Exception\DefaultException;
use App\Core\Exception\LoginException;
use App\Enums\LoginEnums;
use EasySwoole\EasySwoole\Config;

class Jwt extends BaseComponent
{
    
    protected $_secretKey = '\dkGdtzkajseiql5nc';
    
    public function __construct($secretKey = '')
    {
        $this->_secretKey = $secretKey;
    }
    
    /**
     * 设置密钥
     * @param $secretKey
     * @return $this
     */
    public function setSecretKey($secretKey)
    {
        $this->_secretKey = $secretKey;
        return $this;
    }
    
    /**
     * 生成JWT-TOKEN
     * @param array $data
     * @param null $expire
     * @return string
     */
    public function generalToken($data = [], $expire = null) : string
    {
        if ($expire === null) {
            $expire = time() + 3600;
        }
        $jwtObject = \EasySwoole\Jwt\Jwt::getInstance()->setSecretKey($this->_secretKey)->publish();
        
        $jwtObject->setAud('user')->setExp($expire)->setIat(time())->setIss('adqaadsa')
            ->setJti(md5(time()))->setSub("ss")->setData($data);
        
        return $jwtObject->__toString();
    }
    
    /**
     * 校验JWT-TOKEN
     * @param string $token
     * @return \App\Core\Output|void
     * @throws \EasySwoole\Jwt\Exception
     */
    public function validateToken($token = '')
    {
        try{
            $jwtObject = \EasySwoole\Jwt\Jwt::getInstance()->setSecretKey($this->_secretKey)->decode($token);
            
            $status = $jwtObject->getStatus();
            if (Config::getInstance()->getConf('ENV') == 'dev') {
                var_dump($jwtObject->getData());
            }
            switch ($status) {
                case  1:
                    $result = $jwtObject->getData();
                    $result['jwt_exp'] = $jwtObject->getExp();
                    return $this->success($result);
                    break;
                case  -1:
                    throw new LoginException(LoginEnums::NO_LOGIN, '登陆失效');
                    break;
                case  -2:
                    if (Config::getInstance()->getConf('ENV') == 'produce') {
                        throw new LoginException(LoginEnums::NO_LOGIN, '登陆过期');
                    }
                    break;
            }
            
            throw new LoginException(LoginEnums::NO_LOGIN, '登陆过期');
        }catch (\Throwable $e){
            throw new LoginException(LoginEnums::NO_LOGIN, $e->getMessage());
        }
    }
}